<template>
  <div class="bg-f2">
    <div class="bg-f2 bg-fff">
      <div class="addMargin">
        <el-button class="addRole btnSizeStyle" icon="el-icon-plus" :disabled="quanxianBtns.btn1" @click="addRole('添加资产分组')">添加分组</el-button>
      </div>
      <el-drawer title="我是标题" :visible.sync="increased" :with-header="false" :wrapperClosable="false">
        <div class="addUer_title">
          <span>{{ title }}</span>
          <i class="el-icon-close addUer_icon" @click="offDrawer('ruleForm')"></i>
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px">
          <el-row>
            <el-col :span="23">
              <el-form-item label="分组名称：" prop="sbzmc">
                <el-input v-model.trim="ruleForm.sbzmc" clearable placeholder="填写分组名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="forms_fooer">
            <el-button class="btnSizeStyle" @click="offDrawer('ruleForm')">取 消</el-button>
            <el-button type="primary" class="btnSizeStyle" @click="submitForm(title, 'ruleForm')" v-preventReClick>确 定</el-button>
          </div>
        </el-form>
      </el-drawer>
      <el-card>
        <el-table
          :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
          :data="roleList"
          stripe
          max-height="560"
          style="width: 100%"
          :default-sort="{ prop: 'zcsl', order: 'deviceName' }"
          v-loading="tableLoad"
          border
          @sort-change="sortthiscolumn"
        >
          <!-- 提示语句 -->
          <template slot="empty">{{ tableMessage }}</template>
          <el-table-column type="index" label="序号" min-width="50" align="center"></el-table-column>
          <el-table-column prop="sbzmc" label="分组名称"></el-table-column>
          <el-table-column prop="zcsl" sortable label="资产数">
            <template slot-scope="scope">
              <span :class="[scope.row.zcsl < 1 ? '' : 'haveLinks']" @click="goxianqing(scope.row)">{{ scope.row.zcsl }}</span>
            </template>
          </el-table-column>
          <el-table-column label="添加人" prop="createBy" min-width="100"></el-table-column>
          <el-table-column prop="CJSJ" label="创建时间">
            <template slot-scope="scope">{{ scope.row.tjsj | dateFormat }}</template>
          </el-table-column>
          <el-table-column label="操作" align="right">
            <template slot-scope="scope">
              <el-button type="text" :disabled="quanxianBtns.btn5" @click="goAddShe(scope.row)">添加设备</el-button>
              <span class="operation"></span>
              <el-button type="text" :disabled="quanxianBtns.btn2" @click="addRole('编辑资产分组', scope.row)">编辑</el-button>
              <span class="operation"></span>
              <el-tooltip class="item" effect="dark" content="该分组绑有资产，不可删除！" :disabled="scope.row.zcsl > 0 ? false : true" placement="top-end">
                <el-button type="text" :disabled="quanxianBtns.btn3" class="color_f56f6f" @click="deteleRole(scope.row)">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog title="删除" :visible.sync="dialogVisible" width="30%">
          <span>您确定要删除吗？</span>
          <span slot="footer" class="dialog-footer">
            <el-button class="btnSizeStyle" @click="dialogVisible = false">取 消</el-button>
            <el-button class="btnSizeStyle" type="primary" @click="deleteItem2" v-preventReClick>确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加设备 -->
        <el-dialog :visible.sync="dialogVisible2" width="45.8%" :close-on-click-modal="false" @close="offFZ">
          <span slot="title" class="dialogTitle">添加设备</span>
          <ul class="addSheBei">
            <li>
              <div class="select2">
                <span>辖区:</span>
                <el-cascader
                  v-model="addShebei.xiaqu"
                  @expand-change="handleChange"
                  ref="cascaderList"
                  class="selectItem2"
                  clearable
                  :props="{
                    lazy: ifLazy,
                    checkStrictly: true,
                    lazyLoad: lazyLoadAdd,
                  }"
                ></el-cascader>
                <!-- <el-cascader
                placeholder="请选择 / 搜索"
                v-model="addShebei.xiaqu"
                filterable
                :options="cityOptions"
                :props="{ expandTrigger: 'hover', checkStrictly: true }"
                clearable
                class="selectItem2"
                ></el-cascader>-->
              </div>
            </li>
            <li>
              <div class="select2">
                <span>设备类型:</span>
                <el-cascader v-model.trim="addShebei.sblx" :options="shebeilxOptions" :props="{ checkStrictly: true }" filterable clearable class="selectItem2"></el-cascader>
              </div>
            </li>
            <li>
              <div class="suosouBox">
                <el-input placeholder="输入设备名称或设备IP" v-model.trim="addShebei.ss" clearable class="selectItem3"></el-input>
                <el-button class="btnSizeStyle" type="primary" size="mini" @click="getShebeiList('搜索')">搜索</el-button>
              </div>
            </li>
          </ul>
          <el-table
            ref="multipleTable"
            style="margin-top: 50px"
            max-height="560"
            @select="isCheck2"
            @select-all="isCheckAll2"
            border
            :data="addSheBeiName"
            highlight-current-row
            :default-sort="{ prop: 'zcmc', order: 'descending' }"
            :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
          >
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column type="index" label="序号" min-width="50" align="center" />
            <el-table-column label="设备列表" prop="zcmc" sortable show-overflow-tooltip></el-table-column>
            <el-table-column label="设备类型" prop="zclxmc">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.zclxmc1 ? scope.row.zclxmc1 + ' / ' : '' }}</span>
                  <span>{{ scope.row.zclxmc2 ? scope.row.zclxmc2 + ' / ' : '' }}</span>
                  <span>{{ scope.row.zclxmc }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="设备IP" prop="ip" min-width="120"></el-table-column>
            <el-table-column label="端口" prop="gldk"></el-table-column>
          </el-table>
          <span slot="footer">
            <div class="fenyeBox">
              <el-pagination
                background
                layout="prev, pager, next"
                @current-change="addHandleCurrentChange"
                :current-page.sync="addCurrentPage"
                :total="addTotal"
                :hide-on-single-page="paginationValue"
              ></el-pagination>
              <div>
                <el-button class="btnSizeStyle" @click="offFZ" size="small">取 消</el-button>
                <el-button class="btnSizeStyle" type="primary" @click="addSheBeiXiaB" :disabled="addSheBeiName2.length > 0 ? false : true" size="small">确 定</el-button>
              </div>
            </div>
          </span>
        </el-dialog>
        <div class="pageFloat">
          <el-pagination
            background
            small
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { ziC } from '@/utils/allUrl.js'
import { getUrl } from '@/utils/getUrl.js'
import { linkageCity } from '@/utils/linkageCity.js'
// import { endLoading } from '@/utils/loading.js'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'
export default {
  data: function () {
    return {
      currentPage: 1,
      pageSize: 10,
      roleList: [],
      total: 0,
      dialogVisible: false,
      dialogVisible2: false,
      // 辖区
      // cityOptions: [],
      ifLazy: true,
      addSheBeiName: [],
      shebeilxOptions: [], // 设备类型
      addSheBeiName2: [],
      addShebei: {
        xiaqu: '',
        sblx: '',
        ss: '',
      },
      ruleForm: {
        sbzmc: '',
      },
      rules: {
        sbzmc: [
          { required: true, message: '此处为必填项', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^([^\*\#\$\%\【\】\!\！\@\￥\$\[\]\{\}\^\&\*\`\~\"\'<>\/])+$/g, message: '不能输入特殊字符', trigger: 'blur' },
        ],
      },
      deleteID: '', // 删除的id
      increased: false, // 添加分组对话框
      title: '添加资产分组',
      fenzID: '', // 分组添加设备ID
      paginationValue: false, // 数据为一条时隐藏
      addTotal: 0,
      addCurrentPage: 1,
      quanxianBtns: {
        btn1: true,
        btn2: true,
        btn3: true,
        btn4: true,
        btn5: true,
        btn7: true,
      },
      tableLoad: false,
      tableTimer: null,
      tableMessage: '',
      listQuery: {
        sortby: '',
        order: '',
      },
    }
  },
  created: function () {
    this.jurisdictionBtn()
    // 获取用户辖区
    // const city = JSON.parse(getUrl('district'))
    // this.cityOptions = city
    this.getList()
    // 获取设备类型
    this.getShebeilx()
  },
  watch: {
    tableLoad(newVal, oldVal) {
      this.tableTimer = setTimeout(() => {
        if (this.tableLoad) {
          this.tableLoad = false
          this.roleList = []
          this.tableMessage = tableMessageText
          // this.total = 0
        }
      }, timeLoad)
    },
  },
  methods: {
    // 获取按钮权限
    jurisdictionBtn() {
      const menus = JSON.parse(getUrl('jurisdiction'))
      menus.forEach((item) => {
        if (item.qxdm === 'ZCZX_ZCGL_ZCZDYFZ') {
          item.children.forEach((item2) => {
            if (item2.qxdm === 'zdyfz:create') {
              this.quanxianBtns.btn1 = false // 添加自定义分组
            } else if (item2.qxdm === 'zdyfz:update') {
              this.quanxianBtns.btn2 = false // 修改自定义分组
            } else if (item2.qxdm === 'zdyfz:delete') {
              this.quanxianBtns.btn3 = false // 删除自定义分组
            } else if (item2.qxdm === 'zdyfzsb:list') {
              this.quanxianBtns.btn4 = false // 自定义分组设备查询
            } else if (item2.qxdm === 'zdyfzsb:create') {
              this.quanxianBtns.btn5 = false // 添加自定义分组设备
            } else if (item2.qxdm === 'zdyfzsb:deletes') {
              this.quanxianBtns.btn7 = false // 删除自定义分组设备
            }
          })
        }
      })
    },
    async lazyLoadAdd(node, resolve) {
      const user = JSON.parse(getUrl('userconter'))
      if (node.level === 0) {
        return resolve(await linkageCity(user.id, node.level + 1))
      } else if (node.level === 1) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value))
      } else if (node.level === 2) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value))
      } else if (node.level === 3) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value, node.label))
      }
    },
    handleChange(e) {
      if (e.length === 3) {
        this.ifLazy = false
      } else {
        this.ifLazy = true
      }
    },
    sortthiscolumn(column) {
      // 排序
      this.tableLoad = true // 加载中样式
      if (column.order === 'descending') {
        this.listQuery.sortby = column.prop.toUpperCase()
        this.listQuery.order = 'DESC' // 降序
      } else if (column.order === 'ascending') {
        this.listQuery.sortby = column.prop.toUpperCase()
        this.listQuery.order = 'ASC' // 升序
      } else {
        this.listQuery.sortby = ''
        this.listQuery.order = '' // 没有排序
      }
      this.getList()
    },
    // 获取数据
    getList() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const user = JSON.parse(getUrl('userconter'))
      const params = new URLSearchParams()
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      params.append('YH_ID', user.id)
      params.append('order', this.listQuery.sortby) // 排序字段
      params.append('sort', this.listQuery.order) // DESC降序 ASC升序
      this.setList(params)
    },
    async setList(params) {
      const { data: res } = await this.$http.post(`${ziC}zdyfz/list`, params)
      switch (res.code) {
        case '0000':
          this.roleList = res.data.list
          this.total = res.data.countList
          break
        default:
          this.roleList = []
          this.total = 0
          this.tableMessage = res.message
          break
      }
      this.tableLoad = false // 表格加载中样式
    },
    handleClick(tab, event) {},
    handleSizeChange(newsize) {
      this.currentPage = 1
      this.pageSize = newsize
      this.getList()
    },
    handleCurrentChange(newChange) {
      this.currentPage = newChange
      this.getList()
    },
    // 添加/修改
    addRole(title, scope) {
      if (scope) {
        this.ruleForm = scope
      }
      this.title = title
      this.increased = true
    },
    // 删除
    deteleRole(scope) {
      if (scope.zcsl > 0) {
        return this.$message({
          type: 'error',
          message: '该分组绑有资产，不可删除！',
          center: true,
        })
      }
      this.deleteID = scope.id
      this.dialogVisible = true
    },
    // 删除
    async deleteItem2() {
      const params = new URLSearchParams()
      params.append('ID', this.deleteID)
      const { data: res } = await this.$http.post(`${ziC}zdyfz/delete`, params)
      if (res.code === '0014') {
        return ''
      } else if (res.code !== '0000') {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
      this.$message({
        type: 'success',
        message: res.message,
        center: true,
      })
      this.dialogVisible = false
      this.currentPage = 1
      this.pageSize = 10
      this.getList()
    },
    // 取消按钮
    offDrawer(ruleForm) {
      this.$refs.ruleForm.resetFields()
      this.ruleForm = {
        sbzmc: '',
      }
      this.increased = false
      this.getList()
    },
    // 提交按钮
    submitForm(title, ruleForm) {
      const userid = JSON.parse(getUrl('userconter')).id
      const params = new URLSearchParams()
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (title === '添加资产分组') {
            params.append('SBZMC', this.ruleForm.sbzmc)
            params.append('YH_ID', userid)
            const { data: res } = await this.$http.post(`${ziC}zdyfz/create`, params)
            if (res.code === '0014') {
              return ''
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.currentPage = 1
            this.pageSize = 10
            this.getList()
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.ruleForm = {
              sbzmc: '',
            }
            this.increased = false
          } else {
            params.append('SBZMC', this.ruleForm.sbzmc)
            params.append('YH_ID', userid)
            params.append('ID', this.ruleForm.id)
            const { data: res } = await this.$http.post(`${ziC}zdyfz/update`, params)
            if (res.code === '0014') {
              return ''
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.getList()
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.ruleForm = {
              sbzmc: '',
            }
            this.increased = false
          }
        } else {
          return this.$message({
            type: 'error',
            message: '请填写正确的信息',
            center: true,
          })
        }
      })
    },
    goxianqing(scope) {
      if (scope.zcsl < 1) {
        return
      }
      const btnShow = {
        showBtn2: this.quanxianBtns.btn7,
      }
      this.$router.push({
        name: 'detailsGrouping', // 路由
        params: {
          // 传递参数
          content: scope,
          btnShow,
        },
      })
    },
    // 去添加设备
    goAddShe(scope) {
      this.fenzID = scope.id
      this.dialogVisible2 = true
      // 获取设备信息
      this.getShebeiList('添加')
    },
    // 设备类型
    async getShebeilx() {
      const params = new URLSearchParams()
      params.append('FLXID', 0)
      const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      if (res.code !== '0000') {
        this.shebeilxOptions = []
        return this.$message({
          type: 'error',
          message: '设备类型' + res.message,
          center: true,
        })
      } else {
        const city = JSON.stringify(res.data.list)
        const newCity = city.replace(/id/g, 'value')
        const cityList = newCity.replace(/lxmc/g, 'label')
        this.shebeilxOptions = JSON.parse(cityList)
      }
    },
    // 获取设备列表
    async getShebeiList(val) {
      if (val !== '搜索') {
        // const arr = []
        const user = JSON.parse(getUrl('userconter'))
        const params = new URLSearchParams()
        if (user.xqbmdj === 1) {
          params.append('SF', user.xqbm)
        } else if (user.xqbmdj === 2) {
          params.append('CS', user.xqbm)
        } else if (user.xqbmdj === 3) {
          params.append('QX', user.xqbm)
        } else if (user.xqbmdj === 4) {
          params.append('XZJD', user.xqbm)
        }
        params.append('userId', user.id)
        params.append('M_', this.addCurrentPage)
        params.append('N_', 10)
        // params.append('BDZT', 0)
        params.append('ZCFZID_BH', this.fenzID)
        const { data: res } = await this.$http.post(`${ziC}zcgl/selectZiChan`, params)
        if (res.code === '0014') {
          return
        } else if (res.code === '0013') {
          this.addTotal = 0
          return (this.addSheBeiName = [])
        } else if (res.code !== '0000') {
          return this.$message({
            type: 'error',
            message: res.message,
            center: true,
          })
        }
        this.addSheBeiName = res.data.list
        this.addTotal = res.data.countList
      } else {
        // const arr = []
        const { xiaqu, sblx, ss } = this.addShebei
        const user = JSON.parse(getUrl('userconter'))
        const params = new URLSearchParams()
        if (xiaqu.length === 1) {
          params.append('SF', xiaqu[0])
        } else if (xiaqu.length === 2) {
          params.append('SF', xiaqu[0])
          params.append('CS', xiaqu[1])
        } else if (xiaqu.length === 3) {
          params.append('SF', xiaqu[0])
          params.append('CS', xiaqu[1])
          params.append('QS', xiaqu[2])
        } else if (xiaqu.length === 4) {
          params.append('SF', xiaqu[0])
          params.append('CS', xiaqu[1])
          params.append('QS', xiaqu[2])
          params.append('XZJD', xiaqu[3])
        }
        params.append('userId', user.id)
        params.append('ZCLX_XJ', sblx[sblx.length - 1] || '')
        params.append('ZCMC_IP_XH', ss)
        params.append('ZCFZID_BH', this.fenzID)
        // params.append('BDZT', 0)
        params.append('M_', this.addCurrentPage)
        params.append('N_', 10)
        const { data: res } = await this.$http.post(`${ziC}zcgl/selectZiChan`, params)
        if (res.code === '0014') {
          return
        } else if (res.code === '0013') {
          this.addTotal = 0
          return (this.addSheBeiName = [])
        } else if (res.code !== '0000') {
          return this.$message({
            type: 'error',
            message: res.message,
            center: true,
          })
        }
        // res.data.list.forEach(item => {
        //   if (item.bdzt === 0) {
        //     arr.push(item)
        //   }
        // })
        this.addSheBeiName = res.data.list
        this.addTotal = res.data.countList
      }
    },
    // 添加设备复选框
    isCheck2(selection, row) {
      this.addSheBeiName2 = selection
    },
    // 添加设备复选框全选
    isCheckAll2(selection, row) {
      this.addSheBeiName2 = selection
    },
    // 关闭分组
    offFZ: function () {
      this.$refs.multipleTable.clearSelection()
      this.addCurrentPage = 1
      this.addSheBeiName2 = []
      this.dialogVisible2 = false
    },
    async addSheBeiXiaB() {
      const arr = []
      if (this.addSheBeiName2.length >= 1) {
        this.addSheBeiName2.forEach((item) => {
          arr.push(item.id)
        })
      }
      const params = new URLSearchParams()
      params.append('SBZ_IDS', this.fenzID)
      params.append('SB_IDS', arr)
      const { data: res } = await this.$http.post(`${ziC}zdyfzsb/create`, params)
      if (res.code === '0014') {
        return ''
      } else if (res.code !== '0000') {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
      this.$message({
        type: 'success',
        message: res.message,
        center: true,
      })
      this.$refs.multipleTable.clearSelection()
      this.addSheBeiName2 = []
      this.dialogVisible2 = false
      this.getList()
    },
    // 添加设备
    addHandleCurrentChange(val) {
      this.addCurrentPage = val
      this.getShebeiList('搜索')
    },
  },
}
</script>
<style lang="scss" scoped>
.addMargin {
  // height: 55px;
  // line-height: 67px;
  margin-bottom: 15px;
  .addRole {
    background: rgba(103, 194, 58, 1);
    font-size: 14px;
    color: #fff;
    text-align: center;
  }
}
.operation {
  display: inline-block;
  margin: 0 5px;
  height: 10px;
  border-left: 1.5px solid #b3b3b3;
}
.el-card {
  border-radius: 0;
}
.el-drawer {
  .addUer_title {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 61px;
    line-height: 61px;
    border-bottom: 1px solid #ededed;
    box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.8);
    > span {
      font-size: 18px;
      font-weight: 600;
    }
    .addUer_icon {
      font-size: 20px;
      font-weight: 700;
      display: flex;
      flex-flow: column;
      justify-content: center;
      cursor: pointer;
    }
  }
  .el-row {
    margin-top: 30px;
  }
  .forms_fooer {
    position: absolute;
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding: 0 20px;
    box-sizing: border-box;
    align-items: center;
    height: 61px;
    line-height: 61px;
    border-top: 1px solid #ededed;
    .users_btn {
      padding: 0 10px;
      height: 36px;
    }
  }
}
.pageFloat {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 48px;
}
.dialogTitle {
  font-size: 15px;
  font-weight: 600;
}
.addSheBei {
  > li:first-child {
    margin-left: 0;
  }
  > li {
    height: 35px;
    line-height: 35px;
    float: left;
    margin-left: 10px;
    .suosouBox {
      display: flex;
      .selectItem3 {
        width: 110%;
      }
      .el-button {
        margin-left: 10px;
      }
    }
  }
  .select2 {
    > span {
      font-weight: 600;
      margin-right: 5px;
    }
    .selectItem2 {
      width: 200px;
      line-height: 0;
    }
  }
}
.el-table {
  border: 1px solid #eaeaea;
  border-bottom: 0;
}
.fenyeBox {
  display: flex;
  justify-content: space-between;
}
</style>
